package com.hkts.naturalgas.flow.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.naturalgas.feign.FeignInterface;
import com.hkts.naturalgas.flow.VO.FlowNodeinfoVo;
import com.hkts.naturalgas.flow.VO.ProcessNodesVo;
import com.hkts.naturalgas.flow.entity.*;
import com.hkts.naturalgas.flow.mapper.FlowTaskInstanceMapper;
import com.hkts.naturalgas.flow.service.*;
import com.hkts.naturalgas.organizational.mapper.HontUserMapper;
import com.hkts.naturalgas.organizational.orgVo.HontUserRolelevelQueryVo;
import com.hkts.naturalgas.organizational.orgVo.HontUserRolelevelVo;
import com.hkts.naturalgas.performance.performanceTo.HontUserTo;
import com.hkts.naturalgas.utils.DateUtils;
import com.hkts.naturalgas.utils.Result;
import com.hkts.naturalgas.utils.ResultUtil;
import com.hkts.naturalgas.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 任务实例表 服务实现类
 * </p>
 *
 * @author zy
 * @since 2022-08-31
 */
@Service
@Transactional
@Slf4j
public class FlowTaskInstanceServiceImpl extends ServiceImpl<FlowTaskInstanceMapper, FlowTaskInstance> implements IFlowTaskInstanceService {


    @Autowired
    private FlowTaskInstanceMapper flowTaskInstanceMapper;
    @Autowired
    private IFlowNodeinfoService iFlowNodeinfoService;
    @Autowired
    private IFlowHistoryService iFlowHistoryService;
    @Autowired
    private IFlowTemplateinfoService iFlowTemplateinfoService;
    @Autowired
    private IFlowInstanceinfoService iFlowInstanceinfoService;
    @Autowired
    private IFlowTaskHandlerService iFlowTaskHandlerService;
    @Autowired
    private FeignInterface feignInterface;
    @Autowired
    private HontUserMapper hontUserMapper;

    @Override
    public IPage<FlowTaskInstance> selectPage(Page<FlowTaskInstance> page, FlowTaskInstance flowTaskInstance) {
        QueryWrapper<FlowTaskInstance> query = Wrappers.query();
        QueryWrapper<FlowTaskInstance> entityWrapper = getEntityWrapper(query, flowTaskInstance);
        return flowTaskInstanceMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<FlowTaskInstance> selectList(FlowTaskInstance flowTaskInstance) {
        QueryWrapper<FlowTaskInstance> query = Wrappers.query();
        QueryWrapper<FlowTaskInstance> entityWrapper = getEntityWrapper(query, flowTaskInstance);
        return flowTaskInstanceMapper.selectList(entityWrapper);
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<FlowTaskInstance> getEntityWrapper(QueryWrapper<FlowTaskInstance> entityWrapper, FlowTaskInstance flowTaskInstance) {
        //条件拼接

        return entityWrapper;
    }

    @Override
    public FlowTaskInstance getFlowTaskInstanceByFlowInstance(String flowInstanceId){
        QueryWrapper<FlowTaskInstance> query = Wrappers.query();
        query.lambda().eq(FlowTaskInstance::getFlowInstanceId,flowInstanceId)
                .eq(FlowTaskInstance::getDel,false);
        FlowTaskInstance flowTaskInstance = flowTaskInstanceMapper.selectOne(query);
        return flowTaskInstance;
    }
    @Override
    public Result<Object> addFlowTaskInstance(FlowInstanceinfo flowInstanceinfo,
                                              FlowTemplateinfo flowTemplateinfo, Integer level) {
        Map<String,String> result=new HashMap<>();
        result.put("finish","false");

        String id=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
        FlowTaskInstance flowTaskInstance=new FlowTaskInstance();
        flowTaskInstance.setId(id);
        flowTaskInstance.setFlowTaskCode(DateUtils.getCurrentDateTimeShort());
        flowTaskInstance.setFlowInstanceId(flowInstanceinfo.getId());
        FlowNodeinfo flowNodeinfo= iFlowNodeinfoService.getFlowNodeinfo(flowTemplateinfo.getId(),flowTemplateinfo.getTemplateVersion(),
               1);
        FlowNodeinfoVo flowNodeinfoVo = null;
        if(flowTemplateinfo.getIsAbove()==1){
        //TODO 根据角色级别 添加任务时 跳过低于这个级别的审批人节点
            flowNodeinfoVo=   iFlowTaskHandlerService.addFlowTaskHandlerOnLevel( flowNodeinfo,level,
                        flowInstanceinfo.getHontDepartmentId(),id,flowInstanceinfo.getIsOrganization());

//             else {
//                 log.error("没有对应节点的审核人员:{}",flowInstanceinfo);
//                 return ResultUtil.error(500,"没有对应节点的审核人员");
//             }
        }
        Integer setpId;
        if(flowNodeinfoVo!=null){
            flowTaskInstance.setFlowNodeId(flowNodeinfoVo.getId());
            setpId=flowNodeinfoVo.getSetpId();
            if(FlowNodeinfo.NODE_TYPE_FINISH.equals(flowNodeinfoVo.getNodeType())){
                result.put("finish","true");
            }
        }else{
            FlowNodeinfo node=iFlowTaskHandlerService.addFlowTaskHandler(flowNodeinfo,flowInstanceinfo.getHontDepartmentId(),id,flowInstanceinfo.getIsOrganization());
            if(node!=null){
                flowTaskInstance.setFlowNodeId(flowNodeinfo.getId());
                setpId=flowNodeinfo.getSetpId();
                if(FlowNodeinfo.NODE_TYPE_FINISH.equals(node.getNodeType())){
                    result.put("finish","true");
                }
            }else {
                log.error("没有对应节点的审核人员:{}",flowInstanceinfo);
                return ResultUtil.error(500,"没有对应节点的审核人员");
            }
        }


        flowTaskInstanceMapper.insert(flowTaskInstance);
        iFlowHistoryService.addFlowHistory(flowTaskInstance,setpId);

        return ResultUtil.data(result);
    }

    @Override
    public Result<Object> approval(String flowInstanceId) {
        log.info("flowInstanceId=>:{}",flowInstanceId);
        //TODO 获取当前登录人
        boolean finishFlag=false;
        HontUserTo u = feignInterface.remoteUserInfo();
        FlowTaskInstance flowTaskInstance= getFlowTaskInstanceByFlowInstance(flowInstanceId);
//        boolean flag=iFlowNodeHandlerService.checkUser(flowTaskInstance.getFlowNodeId(),
//                userid,roleIds);
        boolean flag=iFlowTaskHandlerService.checkUser(flowTaskInstance.getId(),u.getId());
        if(!flag){
            return ResultUtil.error("您没有权限审批此节点");
        }
      //更新当前节点数据
        FlowInstanceinfo flowInstanceinfo=iFlowInstanceinfoService.getById(flowInstanceId);
        FlowHistory flowHistory=
                iFlowHistoryService.getFlowHistoryByTaskId(flowTaskInstance.getId(),flowTaskInstance.getFlowTaskCode(),flowTaskInstance.getFlowNodeId());
        flowHistory.setTaskEndTime(LocalDateTime.now());
        flowHistory.setTaskHandler(u.getId());
        flowHistory.setTaskHandlerName(u.getNickName());
        iFlowHistoryService.updateById(flowHistory);

        FlowNodeinfo flowNodeinfo=
                iFlowNodeinfoService.getById(flowTaskInstance.getFlowNodeId());
        //审批完成 将当前节点修改为下一个节点9
        log.info("当前审批节点：{}，流程实例：{}",flowNodeinfo,flowInstanceinfo);
        if(!FlowNodeinfo.NODE_TYPE_FINISH.equals(flowNodeinfo.getNodeType())){
            FlowNodeinfo nextFlowNodeinfo=iFlowNodeinfoService.getFlowNodeinfo(flowNodeinfo.getTemplateId(),flowNodeinfo.getTemplateVersion(),flowNodeinfo.getSetpId()+1);
            boolean skip=iFlowTaskHandlerService.skipNodeInfo(u,nextFlowNodeinfo,flowInstanceinfo.getHontDepartmentId(),flowInstanceinfo.getIsOrganization());
            if (skip) {
                if (!FlowNodeinfo.NODE_TYPE_FINISH.equals(nextFlowNodeinfo.getNodeType())) {
                    nextFlowNodeinfo = iFlowNodeinfoService.getFlowNodeinfo(flowNodeinfo.getTemplateId(), flowNodeinfo.getTemplateVersion(), nextFlowNodeinfo.getSetpId() + 1);
                }else {
                    flowInstanceinfo.setFlowEndTime(LocalDateTime.now());
                    flowInstanceinfo.setFlowStatus(FlowInstanceinfo.FLOW_STATUS_FINISH);
                    iFlowInstanceinfoService.updateById(flowInstanceinfo);
                    flowTaskInstanceMapper.deleteById(flowTaskInstance.getId());
                    iFlowTaskHandlerService.deleteByTaskId(flowTaskInstance.getId());
                    finishFlag=true;
                    //TODO 流程结束，调取抄送节点
                    return ResultUtil.data(finishFlag);
                }
            }
            flowTaskInstance.setFlowNodeId(nextFlowNodeinfo.getId());
            flowTaskInstance.setFlowTaskCode(DateUtils.getCurrentDateTimeShort());
            flowTaskInstanceMapper.updateById(flowTaskInstance);
            iFlowTaskHandlerService.updateFlowTaskHandler(flowTaskInstance,
                    flowInstanceinfo.getHontDepartmentId(),flowInstanceinfo.getIsOrganization());
            iFlowHistoryService.addFlowHistory(flowTaskInstance,nextFlowNodeinfo.getSetpId());
            return ResultUtil.data(finishFlag);
        }else {

            flowInstanceinfo.setFlowEndTime(LocalDateTime.now());
            flowInstanceinfo.setFlowStatus(FlowInstanceinfo.FLOW_STATUS_FINISH);
            iFlowInstanceinfoService.updateById(flowInstanceinfo);
            flowTaskInstanceMapper.deleteById(flowTaskInstance.getId());
            iFlowTaskHandlerService.deleteByTaskId(flowTaskInstance.getId());
            finishFlag=true;
            //TODO 流程结束，调取抄送节点
        }
        return ResultUtil.data(finishFlag);
    }

    @Override
    public Result<Object> approval(String flowInstanceId,String assessmentStatus) {
        log.info("flowInstanceId=>:{}",flowInstanceId);
        //TODO 获取当前登录人
        boolean finishFlag=false;
        HontUserTo u = feignInterface.remoteUserInfo();
        FlowTaskInstance flowTaskInstance= getFlowTaskInstanceByFlowInstance(flowInstanceId);
//        boolean flag=iFlowNodeHandlerService.checkUser(flowTaskInstance.getFlowNodeId(),
//                userid,roleIds);
        if (flowTaskInstance == null){
            return ResultUtil.error(201,"该节点已被其他人审批");
        }
        boolean flag=iFlowTaskHandlerService.checkUser(flowTaskInstance.getId(),u.getId());
        if(!flag){
            return ResultUtil.error("您没有权限审批此节点");
        }
        //更新当前节点数据
        FlowInstanceinfo flowInstanceinfo=iFlowInstanceinfoService.getById(flowInstanceId);
        FlowHistory flowHistory=
                iFlowHistoryService.getFlowHistoryByTaskId(flowTaskInstance.getId(),flowTaskInstance.getFlowTaskCode(),flowTaskInstance.getFlowNodeId());
        flowHistory.setTaskEndTime(LocalDateTime.now());
        flowHistory.setTaskHandler(u.getId());
        flowHistory.setTaskHandlerName(u.getNickName());
        flowHistory.setAssessmentStatus(String.valueOf(assessmentStatus));
        iFlowHistoryService.updateById(flowHistory);

        FlowNodeinfo flowNodeinfo=
                iFlowNodeinfoService.getById(flowTaskInstance.getFlowNodeId());
        //审批完成 将当前节点修改为下一个节点
        log.info("当前审批节点：{}，流程实例：{}",flowNodeinfo,flowInstanceinfo);
        if(!FlowNodeinfo.NODE_TYPE_FINISH.equals(flowNodeinfo.getNodeType())){
            if (assessmentStatus.equals("审核拒绝")){
                flowInstanceinfo.setFlowEndTime(LocalDateTime.now());
                flowInstanceinfo.setFlowStatus(FlowInstanceinfo.FLOW_STATUS_FINISH);
                iFlowInstanceinfoService.updateById(flowInstanceinfo);
                flowTaskInstanceMapper.deleteById(flowTaskInstance.getId());
                iFlowTaskHandlerService.deleteByTaskId(flowTaskInstance.getId());
                finishFlag=true;
                //TODO 流程结束，调取抄送节点
                return ResultUtil.data(finishFlag);
            }
            FlowNodeinfo nextFlowNodeinfo=iFlowNodeinfoService.getFlowNodeinfo(flowNodeinfo.getTemplateId(),flowNodeinfo.getTemplateVersion(),flowNodeinfo.getSetpId()+1);
            boolean skip=iFlowTaskHandlerService.skipNodeInfo(u,nextFlowNodeinfo,flowInstanceinfo.getHontDepartmentId(),flowInstanceinfo.getIsOrganization());
            if (skip) {
                if (!FlowNodeinfo.NODE_TYPE_FINISH.equals(nextFlowNodeinfo.getNodeType())) {
                    nextFlowNodeinfo = iFlowNodeinfoService.getFlowNodeinfo(flowNodeinfo.getTemplateId(), flowNodeinfo.getTemplateVersion(), nextFlowNodeinfo.getSetpId() + 1);
                }else {
                    flowInstanceinfo.setFlowEndTime(LocalDateTime.now());
                    flowInstanceinfo.setFlowStatus(FlowInstanceinfo.FLOW_STATUS_FINISH);
                    iFlowInstanceinfoService.updateById(flowInstanceinfo);
                    flowTaskInstanceMapper.deleteById(flowTaskInstance.getId());
                    iFlowTaskHandlerService.deleteByTaskId(flowTaskInstance.getId());
                    finishFlag=true;
                    //TODO 流程结束，调取抄送节点
                    return ResultUtil.data(finishFlag);
                }
            }
            flowTaskInstance.setFlowNodeId(nextFlowNodeinfo.getId());
            flowTaskInstance.setFlowTaskCode(DateUtils.getCurrentDateTimeShort());
            flowTaskInstanceMapper.updateById(flowTaskInstance);
            iFlowTaskHandlerService.updateFlowTaskHandler(flowTaskInstance,
                    flowInstanceinfo.getHontDepartmentId(),flowInstanceinfo.getIsOrganization());
            iFlowHistoryService.addFlowHistory(flowTaskInstance,nextFlowNodeinfo.getSetpId());
            return ResultUtil.data(finishFlag);
        }else {

            flowInstanceinfo.setFlowEndTime(LocalDateTime.now());
            flowInstanceinfo.setFlowStatus(FlowInstanceinfo.FLOW_STATUS_FINISH);
            iFlowInstanceinfoService.updateById(flowInstanceinfo);
            flowTaskInstanceMapper.deleteById(flowTaskInstance.getId());
            iFlowTaskHandlerService.deleteByTaskId(flowTaskInstance.getId());
            finishFlag=true;
            //TODO 流程结束，调取抄送节点
        }
        return ResultUtil.data(finishFlag);
    }

    @Override
    public Result<Object> getApprovalTimeline(String flowInstanceId,String templateId,String templateVersion) {
        ProcessNodesVo processNodesVo=new ProcessNodesVo();
        if(StringUtils.isBlank(flowInstanceId)&&StringUtils.isBlank(templateId)){
            return ResultUtil.error("传参错误");
        }
        if(StringUtils.isBlank(templateId)){
            FlowInstanceinfo flowInstanceinfo=iFlowInstanceinfoService.getById(flowInstanceId);
            templateId=flowInstanceinfo.getTemplateId();
            templateVersion=flowInstanceinfo.getTemplateVersion();
        }
        List<FlowNodeinfo> flowNodeinfos= iFlowNodeinfoService.selectList(templateId,templateVersion);
        List<String> nodes=flowNodeinfos.stream().map(FlowNodeinfo::getNodeName).collect(Collectors.toList());
        List<String> taskNames=new ArrayList<>();
        taskNames.add("提交考核");
        taskNames.addAll(nodes);
        taskNames.add("结束考核");
        if(StringUtils.isBlank(flowInstanceId)){
            processNodesVo.setCurrentTaskIndex(0);
        }else {
            FlowTaskInstance flowTaskInstance=getFlowTaskInstanceByFlowInstance(flowInstanceId);
            if(flowTaskInstance!=null){
                List<FlowNodeinfo> indexFlowNodeinfos=flowNodeinfos.stream().filter(t->flowTaskInstance.getFlowNodeId().equals(t.getId())).collect(Collectors.toList());
                processNodesVo.setCurrentTaskIndex(indexFlowNodeinfos.get(0).getSetpId());
            }else {
                FlowNodeinfo indexFlowNodeinfos=flowNodeinfos.stream().max(Comparator.comparing(FlowNodeinfo::getSetpId)).get();
                processNodesVo.setCurrentTaskIndex(indexFlowNodeinfos.getSetpId()+1);
            }
        }
        processNodesVo.setTaskNames(taskNames);
        return ResultUtil.data(processNodesVo);
    }

    @Override
    public Integer getIsEnableOpinion(String flowInstanceId) {
        FlowTaskInstance flowTaskInstance=getFlowTaskInstanceByFlowInstance(flowInstanceId);
        FlowNodeinfo flowNodeinfo=iFlowNodeinfoService.getById(flowTaskInstance.getFlowNodeId());
        return flowNodeinfo.getIsEnableOpinion();
    }

    @Override
    public Integer getInitIsEnableOpinion(String templateId,String templateVersion) {
        // 添加流程发起人数据
//        HontUserTo u = feignInterface.remoteUserInfo();
//        HontUserRolelevelQueryVo hontUserRolelevelQueryVo=new HontUserRolelevelQueryVo();
//        hontUserRolelevelQueryVo.setUserId(u.getId());
//        List<HontUserRolelevelVo> hontUserRolelevelVos=
//                hontUserMapper.getHontUserAndRoleAndLevel(hontUserRolelevelQueryVo);
//        HontUserRolelevelVo hontUserRolelevelVo=hontUserRolelevelVos.get(0);
//        FlowNodeinfo flowNodeinfo= iFlowNodeinfoService.getFlowNodeinfo(templateId,templateVersion,
//                1);
//        FlowNodeinfoVo flowNodeinfoVo=iFlowTaskHandlerService.getFlowNodeinfoOnLevel(flowNodeinfo,hontUserRolelevelVo.getRoleLevel());
//        log.info("用户信息==>{},流程模板id==>{},流程节点信息：=>{}",hontUserRolelevelVos,templateId,flowNodeinfoVo);
       FlowTemplateinfo flowTemplateinfo= iFlowTemplateinfoService.getById(templateId);
        return flowTemplateinfo.getIsEnableOpinion();
    }
}
